<?php

use Illuminate\Database\Capsule\Manager as DB;

#[业绩计算控制器]
class CalcController extends CoreController
{
    public function init()
    {
        if (!$this->isCli()) {
            throw new Exception("Go to cli please!", '303');
        }
        parent::init();
    }

    #[重组会员关系]
    public function memberChildrenAction()
    {
        $start_on = $this->get('start_on', 0);
        $end_on = $this->get('end_on', 0);
        DB::table('member')
            ->where('id', '>', $start_on)
            ->where('id', '<=', $end_on)
            ->select('id', 'parent_member_id')
            ->orderBy('id', 'asc')
            ->chunk(100, function ($members) {
                foreach ($members as $member) {
                    if ($member->parent_member_id > 0) {
                        $parent = DB::table('member')->select('id', 'parent_member_id')->find($member->parent_member_id);
                        if (!$parent) {
                            continue;
                        }
                        $this->buildChildren($member, $parent, 1);
                    }
                }
            });
    }

    private function buildChildren($member, $parent, $level = 1)
    {
        $childRow = [
            'member_id' => $parent->id,
            'level' => $level,
            'children_id' => $member->id,
        ];
        DB::table('member_children')->insert($childRow);
        echo $childRow['children_id'], ' : ', $childRow['level'], ' : ', $childRow['member_id'], PHP_EOL;
        if ($parent->parent_member_id > 0) {
            $parent = DB::table('member')->select('id', 'parent_member_id')->find($parent->parent_member_id);
            if ($parent) {
                $this->buildChildren($member, $parent, ++$level);
            }

        }
    }

    #[重新计算个人业绩]
    public function reCalcTotalConsumeAction()
    {
        $start_on = $this->get('start_on', 0);
        $end_on = $this->get('end_on', 0);
        DB::table('member')
            ->where('id', '>', $start_on)
            ->where('id', '<=', $end_on)
            ->whereIn('id', orderModel::query()->selectRaw('if(customer_id>0, customer_id, member_id) as mem_id')->groupBy('mem_id')->pluck('mem_id'))
            // ->whereIn('id', membermergeModel::whereColumn('source_id', 'target_id')->pluck('target_id'))
            ->select('id')
            ->orderBy('id', 'asc')
            ->chunk(200, function ($members) {
                foreach ($members as $member) {
                    $totaler = DB::select('SELECT count(*) as ttr from cs_order a where (a.customer_id=0 and a.member_id=:member_id or a.customer_id=:customer_id) and a.`status`>0 and a.id in (
                        SELECT order_id from cs_order_item b where b.member_id=:id and b.refund_status<2)', ['member_id' => $member->id, 'customer_id' => $member->id, 'id' => $member->id]);
                    $ttr = $totaler[0]->ttr ?: 0;
                    $summer = DB::select('SELECT sum(pay_price) as smr FROM `cs_order` a inner join cs_order_item b on a.id=b.order_id where a.status>0 and b.refund_status<2 and b.`member_id`=:id',
                        ['id' => $member->id]);
                    $smr = $summer[0]->smr ?: 0.00;
                    DB::table('member')->where('id', $member->id)->update(['total_consume_num' => $ttr, 'total_consume' => $smr]);
                    echo $member->id, ":", $ttr, ":", $smr, PHP_EOL;
                }
            });
        echo 'Done', PHP_EOL;
    }

    #[重新计算个人佣金]
    public function reCalcTotalIncomeAction()
    {
        $start_on = $this->get('start_on', 0);
        $end_on = $this->get('end_on', 0);
        DB::table('member')
            ->where('id', '>', $start_on)
            ->where('id', '<=', $end_on)
            ->where('level', '>', 1)
            ->select('id')
            ->orderBy('id', 'asc')
            ->chunk(200, function ($members) {
                foreach ($members as $member) {
                    $agent_cms  = DB::table('agent_reward')->where('agent_id', $member->id)->where('status', '>=', 0)->sum('commission');
                    $gudong_cms = DB::table('gudong_reward')->where('gudong_id', $member->id)->where('status', '>=', 0)->sum('commission');
                    $qudai_cms  = DB::table('qudai_reward')->where('qudai_id', $member->id)->where('status', '>=', 0)->sum('commission');
                    $tuike_cms  = DB::table('tuike_reward')->where('tuike_id', $member->id)->where('status', '>=', 0)->sum('commission');
                    $smr = $agent_cms + $gudong_cms + $qudai_cms + $tuike_cms;
                    DB::table('member')->where('id', $member->id)->update(['total_income' => $smr]);

                    echo $member->id, ":", $smr, PHP_EOL;
                }
            });
        echo 'Done', PHP_EOL;
    }

    #[重新计算直推业绩]
    public function reCalcDirectConsumeAction()
    {
        $start_on = $this->get('start_on', 0);
        $end_on = $this->get('end_on', 0);
        DB::table('member')
            ->where('id', '>', $start_on)
            ->where('id', '<=', $end_on)
            ->select('id')
            ->orderBy('id', 'asc')
            ->chunk(200, function ($members) {
                foreach ($members as $member) {
                    if(DB::table('member')->where('parent_member_id', $member->id)->exists()) {
                        $totaler = DB::select('SELECT sum(total_consume_num) as tns from cs_member where parent_member_id=:id',
                            ['id' => $member->id]);
                        $tns     = $totaler[0]->tns;
                        $summer  = DB::select('SELECT sum(total_consume) as cns from cs_member where parent_member_id=:id',
                            ['id' => $member->id]);
                        $cns     = $summer[0]->cns;
                        DB::table('member')->where('id', $member->id)->update(['direct_consume_num' => $tns, 'direct_consume' => $cns]);
                    }else{
                        $tns     = 0;
                        $cns     = 0.00;
                        DB::table('member')->where('id', $member->id)->update(['direct_consume_num' => 0, 'direct_consume' => 0]);
                    }
                    echo $member->id, ':', $tns, ':', $cns, PHP_EOL;
                }
            });
        echo 'Done', PHP_EOL;
    }

    #[重新计算团队业绩]
    public function reCalcTeamConsumeAction()
    {
        $start_on = $this->get('start_on', 0);
        $end_on = $this->get('end_on', 0);
        DB::table('member')
            ->where('id', '>', $start_on)
            ->where('id', '<=', $end_on)
            ->where('level', '<=', 1)
            ->select('id', 'team_consume', 'team_consume_num')
            ->orderBy('id', 'asc')
            ->chunk(200, function ($members) {
                foreach ($members as $member) {
                    $totaler = DB::select('SELECT sum(total_consume_num) as tns from cs_member where id=:id or id in (SELECT children_id from cs_member_children where `member_id`=:member_id)',
                        ['id' => $member->id, 'member_id' => $member->id]);
                    $tns = $totaler[0]->tns;
                    $summer = DB::select('SELECT sum(total_consume) as cns from cs_member where id=:id or id in (SELECT children_id from cs_member_children where `member_id`=:member_id)',
                        ['id' => $member->id, 'member_id' => $member->id]);
                    $cns = $summer[0]->cns;

                    if ($member->team_consume_num != $tns) {
                        DB::table('member')->where('id', $member->id)->update(['team_consume_num' => $tns]);
                    }
                    if ($member->team_consume < $cns) {
                        DB::table('member')->where('id', $member->id)->update(['team_consume' => $cns]);
                        echo $member->id, ':', $cns, PHP_EOL;
                    }else{
                        echo $member->id, 'equal or great, jump', PHP_EOL;
                    }
                }
            });
        echo 'Done', PHP_EOL;
    }

    #[重新计算团队业绩单数]
    public function reCalcTeamConsumeNumAction()
    {
        $start_on = $this->get('start_on', 0);
        $end_on = $this->get('end_on', 0);
        DB::table('member')
            ->where('id', '>', $start_on)
            ->where('id', '<=', $end_on)
            ->select('id', 'team_consume_num')
            ->orderBy('id', 'asc')
            ->chunk(200, function ($members) {
                foreach ($members as $member) {
                    $totaler = DB::select('SELECT sum(total_consume_num) as tns from cs_member where id=:id or id in (SELECT children_id from cs_member_children where `member_id`=:member_id)',
                        ['id' => $member->id, 'member_id' => $member->id]);
                    $tns = $totaler[0]->tns;
                    DB::table('member')->where('id', $member->id)->update(['team_consume_num' => $tns]);
                    echo $member->id, ':', $tns, PHP_EOL;
                }
            });
        echo 'Done', PHP_EOL;
    }

}
